package com.design.twords.controller;

import android.util.Log;

import com.design.twords.config.ConfigData;
import com.design.twords.config.ConstantValue;
import com.design.twords.database.UserConfig;
import com.design.twords.database.Word_learn;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

/**
 * Create by Alen
 * Time:  11:06
 */
public class WordController {

    public static final String TAG = "WordController";


    // 新学模式
    public static final int NEW_LEARN = 1;
    // 及时复习模式
    public static final int REVIEW_AT_TIME = 2;
    // 一般复习模式（浅度&深度）
    public static final int REVIEW_GENERAL = 3;
    // 学习完毕
    public static final int TODAY_MASK_DONE = 4;


    // 当前ID
    public static long currentWordId;
    // 当前模式
    public static int currentMode;
    public static String wordBook;

    //需要学习的单词，需要复习的单词
    // 候选需要学习的单词
    public static List<Long> needLearnWord = new ArrayList<>();

    // 候选需要复习的单词
    public static List<Long> needReviewWord = new ArrayList<>();

    // 用于存放本轮刚学习过的单词，以便及时复习
    public static List<Long> justLearnedWord = new ArrayList<>();


    //生成待选单词列表
    public static void setLearnWordsList(long lastStartTime){
        needLearnWord.clear();
        needReviewWord.clear();
        justLearnedWord.clear();

        //更新上次启动时间
        UserConfig userConfig = new UserConfig();
        userConfig.setLastStartTime(TimeController.getCurrentTimeStamp());
        userConfig.updateAll("userId = ?", ConfigData.getUserId());

        Log.i(TAG, "正在生成新词列表");
        List<UserConfig> all = LitePal.where("userId = ?", ConfigData.getUserId()).find(UserConfig.class);
        //每天学习的单词数
        int idaywords = all.get(0).getDaywords();
        wordBook = ConstantValue.getTypeById(all.get(0).getCurrentBookId());
        Log.i(TAG, "idaywords:"+idaywords);
        //先选出 上次选出来的但是没有及时学习的单词
        // isNeedLearned 标识是否选中过 justLearned 表示是否学习过
        List<Word_learn> needLearnWordList = LitePal.where("isNeedLearned = ? and justLearned = ? and needLearnDate <= ?", "1", "0", TimeController.getCurrentDate() + "")
                .select("wordId").find(Word_learn.class);
        //获取没学过的新词
        List<Word_learn> noLearnWordList = LitePal.where("isNeedLearned = ? and isLearned = ?", "0", "0").select("wordId").find(Word_learn.class);

        Log.i(TAG, "needLearnWordList.size"+needLearnWordList.size());
        Log.i(TAG, "noLearnWordList.size"+noLearnWordList.size());

        //判断两次点击是否为同一天
        if(!TimeController.isTheSameDay(lastStartTime, TimeController.getCurrentTimeStamp())){
            Log.i(TAG, "is a new day");

            //如果当前需要学习的单词数量小于每天制定的计划
            //需要从数据库中找一些新的单词加进去

            if(needLearnWordList.size() < idaywords){
                Log.i(TAG, "the word has not enough");
                int differ = idaywords - needLearnWordList.size();

                //打乱未学习的单词列表 并从中找出 differ 个单词
                int [] numbList = NumberController.getRandomNumberList(0, noLearnWordList.size()-1, differ);
                //将数据存入到 需要学习的单词表中
                for(int i : numbList){
                    needLearnWord.add(noLearnWordList.get(i).getWordId());
                    //更新数据库数据 需要学习 需要学习的时间点
                    Word_learn word_learn = new Word_learn();
                    word_learn.setIsNeedLearned(1);
                    word_learn.setNeedLearnDate(TimeController.getCurrentDate());
                    word_learn.updateAll("wordId = ?", noLearnWordList.get(i).getWordId() + "");
                }
                //将之前的单词加入到候选列表
                if(!needLearnWordList.isEmpty()){
                    for(Word_learn word_learn :needLearnWordList){
                        needLearnWord.add(word_learn.getWordId());
                    }
                }
            }
            //待选单词足够满足每日单词量
            else{
                Log.i(TAG, "the word is enough");
                int i = 0;
                for(Word_learn word_learn : needLearnWordList){
                    i++;
                    if (i <= idaywords){
                        needLearnWord.add(word_learn.getWordId());
                    }else
                        break;
                }
            }
        }else {
            //同一天的话 直接用待选单词
            Log.i(TAG, "is the same day");
            int i = 0;
            for(Word_learn word_learn : noLearnWordList){
                i++;
                if (i <= idaywords){
                    needLearnWord.add(word_learn.getWordId());
                }else
                    break;
            }

        }
        Log.i(TAG,"setLearnWordsList");
        Log.i(TAG, needLearnWord.toString());

    }

    //生成复习单词列表
    public static void setReviewWordsList(){
        needReviewWord.clear();
        justLearnedWord.clear();

        Log.i(TAG, "正在生成复习列表");
        //刚刚学过还没复习的单词
        List<Word_learn> noReviewWordList = LitePal.where("justLearned = ? and isLearned = ?", "1", "0").select("wordId").find(Word_learn.class);
        //已经学过 但是掌握程度没有达到10
        List<Word_learn> noDeepReviewWordList = LitePal.where("isLearned = ? and masterDegree < ?", "1", "10").select("wordId").find(Word_learn.class);
        //掌握程度达到10的
        List<Word_learn> deepReviewWordList = LitePal.where("masterDegree = ?", "10").select("wordId").find(Word_learn.class);

        //首先从掌握程度大的中挑选单词
        //如果掌握程度达到10的 能满足每日复习次数要求 就从中挑出单词

        for(Word_learn word : deepReviewWordList){
            switch (word.getDeepMasterTimes()){
                //根据深度复习次数进行相应处理
                //要是深度次数为0，且两者时间之差为大于4天，说明及时未深度复习 掌握程度-2
                case 0:
                    if (TimeController.daysInternal(word.getLastMasterTime(), TimeController.getCurrentDate()) > 4){
                        Word_learn word_learn = new Word_learn();
                        word_learn.setMasterDegree(8);
                        word_learn.updateAll("wordId = ?", word.getWordId() + "");
                    }
                    needReviewWord.add(word.getWordId());
                    break;
                case 1:
                    if (TimeController.daysInternal(word.getLastMasterTime(), TimeController.getCurrentDate()) > 5){
                        Word_learn word_learn = new Word_learn();
                        word_learn.setMasterDegree(8);
                        word_learn.updateAll("wordId = ?", word.getWordId() + "");
                    }
                    needReviewWord.add(word.getWordId());
                    break;
                case 2:
                    if (TimeController.daysInternal(word.getLastMasterTime(), TimeController.getCurrentDate()) > 8){
                        Word_learn word_learn = new Word_learn();
                        word_learn.setMasterDegree(8);
                        word_learn.updateAll("wordId = ?", word.getWordId() + "");
                    }
                    needReviewWord.add(word.getWordId());
                    break;

            }
        }

        //深度掌握的单词不够
        //从浅掌握的单词中挑
            //把需浅度复习的单词也一并加入到候选复习单词列表
        for (Word_learn word : noDeepReviewWordList) {
            needReviewWord.add(word.getWordId());

        }
        //把需及时复习的单词也一并加入到候选复习单词列表
        for (Word_learn word : noReviewWordList) {
            needReviewWord.add(word.getWordId());
        }
        Log.i(TAG, "setReviewWordsList: ");
        Log.i(TAG, needReviewWord.toString());
    }

    //工作模式
    public static int whatToDo(){
        if (!needLearnWord.isEmpty()) {
            if (justLearnedWord.size() > (needLearnWord.size() / 2)) {
                Log.i(TAG, "接下来是随机模式");
                int nowMode = isNewOrReviewAtTime();
                Log.i(TAG, "whatToDo: " + nowMode);
                return nowMode;
            } else {
                Log.i(TAG, "接下来是新学模式");
                return NEW_LEARN;
            }
        } else {
            if (!justLearnedWord.isEmpty()) {
                Log.i(TAG, "接下来是及时复习模式");
                return REVIEW_AT_TIME;
            } else {
                if (!needReviewWord.isEmpty()) {
                    Log.i(TAG, "接下来是一般复习模式");
                    return REVIEW_GENERAL;
                } else {
                    Log.i(TAG, "done");
                    return TODAY_MASK_DONE;
                }
            }
        }
    }

    //随机选择模式
    private static int isNewOrReviewAtTime() {
        return NumberController.getRandomNumber(NEW_LEARN, REVIEW_AT_TIME);
    }

    // 学习单词
    public static long learnNewWord() {
        Log.i(TAG, "learnNewWord");
        Log.i(TAG, "learnNewWord" + "最后是我返回了值");
        Log.i(TAG, "needLearnedWords.size=" + needLearnWord.size());
        if (!needLearnWord.isEmpty()) {
            int index = NumberController.getRandomNumber(0, needLearnWord.size() - 1);
            return needLearnWord.get(index);
        } else
            return -1;
    }

    // 认识表示初学完这个单词
    //不认识则不做处理 后续还会出现
    // 已初学完该单词（未及时复习）
    public static void learnNewWordDone(long wordId, boolean flag) {
        Log.i(TAG, "learnNewWordDone");
        // 移除
        Log.i(TAG, "before　size:" + needLearnWord.size());
        if (flag){
            for (int i = 0; i < needLearnWord.size(); ++i) {
                if (needLearnWord.get(i) == wordId) {
                    needLearnWord.remove(i);
                    break;
                }
            }
            Log.d(TAG, "after size:" + needLearnWord.size());
            // 放进临时需要复习的列表里
            justLearnedWord.add(wordId);
            // 更新数据库数据
            Word_learn word = new Word_learn();
            word.setJustLearned(1);
            word.setToDefault("isNeedLearned");
            word.updateAll("wordId = ?", wordId + "");
        }

    }

    // 及时复习单词
    public static long reviewNewWord() {
        Log.i(TAG, "reviewNewWord: 最后是我返回了值");
        if (!justLearnedWord.isEmpty()) {
            Log.d(TAG, "-1=?" + justLearnedWord.size());
            int index = NumberController.getRandomNumber(0, justLearnedWord.size() - 1);
            return justLearnedWord.get(index);
        } else
            return -1;
    }

    // 及时复习完单词
    public static void reviewNewWordDone(long wordId, boolean isAnswerRight) {
        List<Word_learn> words = LitePal.where("wordId = ?", wordId + "").select("wordId", "word", "masterDegree", "ExamRightNum", "DeepMasterTimes").find(Word_learn.class);
        if (isAnswerRight) {
            // 移除
            for (int i = 0; i < justLearnedWord.size(); ++i) {
                if (justLearnedWord.get(i) == wordId) {
                    justLearnedWord.remove(i);
                    break;
                }
            }
            // 更新数据库数据
            Word_learn word = new Word_learn();
            word.setIsLearned(1);
            // 如果回答正确，加2点掌握度，回答错误，不加掌握程度，继续背
            if (words.get(0).getMasterDegree() < 10) {
                // 掌握程度+2
                if (words.get(0).getMasterDegree() != 8)
                    word.setMasterDegree(words.get(0).getMasterDegree() + 2);
                else
                    word.setMasterDegree(10);
                word.updateAll("wordId = ?", wordId + "");
            } else {
                word.setDeepMasterTimes(words.get(0).getDeepMasterTimes() + 1);
                word.setLastMasterTime(TimeController.getCurrentDate());
            }
            word.setLastReviewTime(TimeController.getCurrentTimeStamp());
            word.updateAll("wordId = ?", wordId + "");
        }
    }

    // 复习单词（随机抽取）
    public static long reviewWord() {
        Log.i(TAG, "reviewOneWord: 最后是我返回了值");
        if (!needReviewWord.isEmpty()) {
            int index = NumberController.getRandomNumber(0, needReviewWord.size() - 1);
            return needReviewWord.get(index);
        } else
            return -1;
    }

    // 复习完该单词
    public static void reviewWordDone(long wordId, boolean isAnswerRight) {
        List<Word_learn> words = LitePal.where("wordId = ?", wordId + "").select("wordId", "word", "masterDegree", "ExamRightNum", "DeepMasterTimes").find(Word_learn.class);
        if (isAnswerRight) {
            // 移除需要复习列表
            for (int i = 0; i < needReviewWord.size(); ++i) {
                if (needReviewWord.get(i) == wordId) {
                    needReviewWord.remove(i);
                    break;
                }
            }
            // 说明只是浅度复习
            if (words.get(0).getMasterDegree() < 10) {
                Word_learn word = new Word_learn();
                // 测试正确次数+1
                word.setExamRightNum(1 + words.get(0).getExamRightNum());
                // 掌握程度+2
                if (words.get(0).getMasterDegree() != 8)
                    word.setMasterDegree(words.get(0).getMasterDegree() + 2);
                else
                    word.setMasterDegree(10);
                word.updateAll("wordId = ?", wordId + "");
            } else {
                // 说明已是处于深度复习阶段
                Word_learn word = new Word_learn();
                word.setDeepMasterTimes(words.get(0).getDeepMasterTimes() + 1);
                word.setLastMasterTime(TimeController.getCurrentDate());
                word.updateAll("wordId = ?", wordId + "");
            }
        }
        // 更新测试次数
        Word_learn word = new Word_learn();
        word.setExamNum(words.get(0).getExamNum() + 1);
        word.updateAll("wordId = ?", wordId + "");
    }

    //删除单词
    public static void removeOneWord(long wordId) {
        Log.i(TAG, "removeOneWord: " + wordId);
        Log.i(TAG, "之前");
        Log.i(TAG, needLearnWord.toString());
        Log.i(TAG, needReviewWord.toString());
        for (int i = 0; i < needLearnWord.size(); ++i) {
            if (wordId == needLearnWord.get(i))
                needLearnWord.remove(i);
        }
        for (int i = 0; i < needReviewWord.size(); ++i) {
            if (wordId == needReviewWord.get(i))
                needReviewWord.remove(i);
        }
        for (int i = 0; i < justLearnedWord.size(); ++i) {
            if (wordId == justLearnedWord.get(i))
                justLearnedWord.remove(i);
        }
        Log.i(TAG, "之后");
        Log.i(TAG, needLearnWord.toString());
        Log.i(TAG, needReviewWord.toString());
    }



}
